package net.alpcontrol.bi.bootstrap.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

import static org.apache.commons.lang3.SystemUtils.getUserDir;

/**
 * Created by wxf on 2020/9/1.
 */
public class ExcelUtils {
    /**
     * 将项目中resources下的文件路径转换为服务器的文件路径
     * @param path(不允许中文)
     * @return
     */
    public static String convertTemplatePath(String path) {
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        FileOutputStream fileOutputStream = null;
        // 将模版文件写入到 服务器的临时目录下 根目录下的resources
        String folder = getUserDir()+"/resources";
        File tempFile = new File(folder + File.separator + path);
        // 文件存在时不再写入
        if (tempFile.exists()) {
            return tempFile.getPath();
//            tempFile.delete();
        }
        File parentFile = tempFile.getParentFile();
        // 判断父文件夹是否存在
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(resourceAsStream);
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];//10M
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return tempFile.getPath();
    }
    //以下为基于模板(适用于多sheet页)的方法：

    public static void exportExcelByTemplate(TemplateExportParams params, Map<String,Object> map, String fileName, HttpServletResponse response) throws Exception {
        defaultExportByTemplate(params, map,fileName,response);
    }
    private static void defaultExportByTemplate(TemplateExportParams params, Map<String,Object> map, String fileName, HttpServletResponse response) throws Exception {
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception {
        OutputStream outputStream=null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();

            workbook.write(outputStream);
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
